import 'package:flutter/material.dart';

/// 这是一个可以指定SafeArea区域背景色的AppBar
/// PreferredSizeWidget提供指定高度的方法
/// 如果没有约束其高度，则会使用PreferredSizeWidget指定的高度

class CustomAppbar extends StatefulWidget implements PreferredSizeWidget {
  final double contentHeight; //从外部指定高度
  final Color backgroundColor; //设置导航栏背景的颜色
  final Widget leadingWidget;
  final Widget trailingWidget;
  final String title;
  final double elevation;
  final TextStyle titleStyle;

  CustomAppbar({
    this.title = '',
    this.leadingWidget,
    this.contentHeight = 48,
    this.elevation = 2,
    this.titleStyle = const TextStyle(fontSize: 17, color: Colors.white),
    this.backgroundColor,
    this.trailingWidget,
  }) : super();

  @override
  State<StatefulWidget> createState() {
    return new _CustomAppbarState();
  }

  @override
  Size get preferredSize => new Size.fromHeight(contentHeight);
}

/// 这里没有直接用SafeArea，而是用Container包装了一层
/// 因为直接用SafeArea，会把顶部的statusBar区域留出空白
/// 外层Container会填充SafeArea，指定外层Container背景色也会覆盖原来SafeArea的颜色
///     var statusheight = MediaQuery.of(context).padding.top;  获取状态栏高度

class _CustomAppbarState extends State<CustomAppbar> {
  Color bgColor;

  @override
  void initState() {
    super.initState();

    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      bgColor = widget.backgroundColor ?? Theme.of(context).primaryColor;
      setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    return new Material(
      elevation: widget.elevation,
      child: new Container(
        color: bgColor,
        child: new SafeArea(
          top: true,
          child: new Container(
//              decoration: new UnderlineTabIndicator(
//                borderSide: BorderSide(width: 1.0, color: Color(0xFFeeeeee)),
//              ),
              height: widget.contentHeight,
              child: new Stack(
                alignment: Alignment.center,
                children: <Widget>[
                  Positioned(
                    left: 0,
                    child: new Container(
                      padding: const EdgeInsets.only(left: 5),
                      child: widget.leadingWidget,
                    ),
                  ),
                  new Center(
                    child: new Text(widget.title, style: widget.titleStyle),
                  ),
                  Positioned(
                    right: 0,
                    child: new Container(
                      padding: const EdgeInsets.only(right: 5),
                      child: widget.trailingWidget,
                    ),
                  ),
                ],
              )),
        ),
      ),
    );
  }
}
